﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using cashbook_psql_cs.BLL;
using cashbook_psql_cs.DAL;
using cashbook_psql_cs.util;
using DocumentFormat.OpenXml.Wordprocessing;

namespace cashbook_psql_cs
{
    public partial class FrmImport: Form
    {
        //将mainForm实例通过构造函数方式传过来，而非重新new一个实例
        private readonly FrmMain _mainForm;
        private readonly RelationBillBLL _billBll = new RelationBillBLL();
        public FrmImport(FrmMain mainForm)
        {
            _mainForm = mainForm;
            InitializeComponent();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ExportHelper.ExportTemplate();
        }

        //点击确定批量导入
        private void button2_Click(object sender, EventArgs e)
        {
            
            string filePath = GetValidatedPath(this.txtFilePath);
            _billBll.CopyExcelDataToDb(filePath);
            // 1. 清空旧数据（可选）
            //_mainForm.DataGridView1.DataSource = null;
            DataTable dt = _billBll.FillDatasByRelationBill();
            // 调试：检查返回的 DataTable 是否有数据
            Console.WriteLine($"返回的数据行数: {dt?.Rows.Count ?? 0}");
            _mainForm.DataGridView1.DataSource = dt;
            //frmMain.DataGridView1.Refresh(); // 强制重绘
            //frmMain.DataGridView1.ResetBindings(); // 通知控件数据已变更
        }

        //取消
        private void button3_Click(object sender, EventArgs e)
        {
            Close();
        }

        //浏览文件
        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Excel文件|*.xlsx;*.xls";
                openFileDialog.Title = "选择Excel文件";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtFilePath.Text = openFileDialog.FileName;
                }
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 获取并验证路径的通用方法
        /// </summary>
        /// <param name="textBox">包含路径的文本框</param>
        /// <returns>验证后的路径，如果无效则返回空字符串</returns>
        public static string GetValidatedPath(TextBox textBox)
        {
            try
            {
                // 基础处理
                string txtpath = textBox.Text.Trim();

                // 空值检查
                if (string.IsNullOrWhiteSpace(txtpath))
                {
                    throw new ArgumentException("路径不能为空");
                }

                // 移除多余引号（如果用户拖放带引号的路径）
                txtpath = txtpath.Trim('"');

                // 验证路径格式
                if (txtpath.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
                {
                    throw new ArgumentException("路径包含非法字符");
                }

                // 自动补全目录分隔符
                if (!txtpath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
                    Directory.Exists(txtpath))
                {
                    txtpath += Path.DirectorySeparatorChar;
                }

                // 转换环境变量（如 %AppData%）
                txtpath = Environment.ExpandEnvironmentVariables(txtpath);

                // 返回标准化的绝对路径
                return Path.GetFullPath(txtpath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"路径无效: {ex.Message}");
                return string.Empty;
            }
        }

        private void FrmImport_Load(object sender, EventArgs e)
        {
            //手动计算屏幕分辨率居中
            Screen screen = Screen.PrimaryScreen;
            this.Left = (screen.WorkingArea.Width - this.Width) / 2;
            this.Top = (screen.WorkingArea.Height - this.Height) / 2;
        }
    }
}
